package com.zbkj.crmeb.task.plat.tiktok;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.config.RestTemplateConfig;
import com.doudian.open.api.order_searchList.OrderSearchListRequest;
import com.doudian.open.api.order_searchList.OrderSearchListResponse;
import com.doudian.open.api.order_searchList.data.OrderSearchListData;
import com.doudian.open.api.order_searchList.data.PostAddr;
import com.doudian.open.api.order_searchList.data.ShopOrderListItem;
import com.doudian.open.api.order_searchList.data.SkuOrderListItem;
import com.doudian.open.api.order_searchList.param.OrderSearchListParam;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.factory.TaskParamsDto;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.handler.orderproduct.OrderProductContext;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.plat.by.dto.Result;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.AbstractPlatOperate;
import com.zbkj.crmeb.task.plat.bieyang.dto.*;
import com.zbkj.crmeb.task.plat.poizon.enums.OrderTypeEnum;
import com.zbkj.crmeb.task.plat.poizon.enums.TikTokMerShopIdEnum;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 抖店订单捞取
 *
 * @author: zxy
 * @date: 2024/1/29 0029 22:08
 * @ClassName: BieYangOrderTask
 */
@Component("tikTokOrderTask")
@Configuration
@Slf4j
public class TikTokOrderTask extends AbstractPlatOperate<TaskParamsDto> implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(TikTokOrderTask.class);
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Resource
    private StoreBrandService storeBrandService;
    @Resource
    private ICategoryMatchService categoryMatchService;
    @Resource
    private PriceUtil priceUtil;
    @Resource
    private MoneyExchangeService moneyExchangeService;
    @Qualifier("tikTokOrderProductHandler")
    @Autowired
    private OrderProductInterface orderProductInterface;

    @XxlJob("tkUploadProduct")
    public void uploadProduct() {
        OrderProductContext orderProductContext = new OrderProductContext();
        orderProductContext.setProductId(XxlJobHelper.getJobParam());
        Result execute = orderProductInterface.execute(orderProductContext);
        DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT, JSON.toJSONString(execute));
    }

    @XxlJob("fetchOrderOfTikTok")
    public void fetch() {
        log.info("fetchOrderOfTikTok入口,{}");
        Calendar calendar = Calendar.getInstance();
        Long endTimeStamp = calendar.getTimeInMillis()/1000;
        // 20天
        calendar.add(Calendar.DATE, -20);
        Long startTimeStamp = calendar.getTimeInMillis()/1000;

        for (TikTokMerShopIdEnum value : TikTokMerShopIdEnum.values()) {
            log.info("TikTokMerShopIdEnum,{}", JSON.toJSONString(value));
//            if (value.getMerId().equals(150)) continue;
            Long page = 0L;
            AccessToken accessToken = AccessTokenBuilder.build(value.getShopId());
            OrderSearchListRequest request = new OrderSearchListRequest();
            OrderSearchListParam param = request.getParam();
            param.setAfterSaleStatusDesc("all");
            param.setCreateTimeStart(startTimeStamp);
            param.setCreateTimeEnd(endTimeStamp);
            param.setOrderType(OrderTypeEnum.ORDINARY.getCode());
            param.setPage(page);
            param.setSize(99L);
            param.setOrderBy("create_time");
            param.setOrderAsc(false);

            List<ShopOrderListItem> shopOrderCollection = new ArrayList<>();
            // 获取订单数据
            while (true) {
                param.setPage(page);
                OrderSearchListResponse response = request.execute(accessToken);
//                log.info("请求抖音响应数据,{}", JSON.toJSONString(response));
                if (response.isSuccess()) {
                    OrderSearchListData data = response.getData();
                    List<ShopOrderListItem> shopOrderList = data.getShopOrderList();
                    if (CollectionUtils.isEmpty(shopOrderList)) {
                        break;
                    }
                    shopOrderCollection.addAll(shopOrderList);
                }else{
                    log.error("请求抖音平台异常,{}", JSON.toJSONString(response));
                    break;
                }
                page++;
            }
            // 获取子单
            List<SkuOrderListItem> skuOrderListItemList = shopOrderCollection.stream().map(ShopOrderListItem::getSkuOrderList).flatMap(List::stream).collect(Collectors.toList());
            // 过滤订单状态不正确的订单
            validateTikTokOrderStatus(skuOrderListItemList);
            if (CollectionUtils.isEmpty(skuOrderListItemList)) {
                continue;
            }
            // 校验订单是否存在
            validateOrderExist(skuOrderListItemList);
            if (CollectionUtils.isEmpty(skuOrderListItemList)) {
                continue;
            }

            List<Integer> ids = new ArrayList<>();
            for (SkuOrderListItem skuOrderListItem : skuOrderListItemList) {
                StoreOrder storeOrder = assembledStoreOrder(skuOrderListItem, value.getMerId());
                // 新增订单
                boolean b = storeOrderService.saveOrUpdate(storeOrder);
                if (!b) {
                    log.error("新增订单异常,{}", JSON.toJSONString(storeOrder));
                    continue;
                }
                StoreOrder queryStoreOrder = storeOrderService.getOne(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getOrderId, storeOrder.getOrderId()).last("limit 1"));
                if (null == queryStoreOrder) {
                    log.error("查询保存订单异常,{}", JSON.toJSONString(storeOrder));
                    continue;
                }
                try {
                    List<StoreOrderInfo> storeOrderInfos = assembledStoreOrderInfo(skuOrderListItem, queryStoreOrder);
                    storeOrderInfoService.saveOrUpdateBatch(storeOrderInfos);
                    log.info("抖店创建订单,{}", JSON.toJSONString(storeOrder));
                    DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT, "抖店创建订单：" + storeOrder.getOrderId());
                } catch (Exception e) {
                    log.error("组装商品数据异常:", e);
                    ids.add(queryStoreOrder.getId());
                    throw new RuntimeException(e);
                }
            }
            if (CollectionUtils.isNotEmpty(ids)) {
                log.error("创建订单异常:");
                // 删除订单
                storeOrderService.removeByIds(ids);
            }

        }
    }

//    private void handleSplitOrder(List<BieYangDataDto> bieYangDataDtos) {
//        if (CollectionUtils.isEmpty(bieYangDataDtos)) {
//            return;
//        }
//        Iterator<BieYangDataDto> iterator = bieYangDataDtos.iterator();
//        List<BieYangDataDto> splitDataDtos = new ArrayList<>();
//        while (iterator.hasNext()) {
//            BieYangDataDto bieYangDataDto = iterator.next();
//            if (null != bieYangDataDto.getInfoSummary() && null != bieYangDataDto.getInfoSummary().getSplit() && bieYangDataDto.getInfoSummary().getSplit()) {
//                splitDataDtos.add(bieYangDataDto);
//                iterator.remove();
//            }
//        }
//        if (CollectionUtils.isEmpty(splitDataDtos)) {
//            return;
//        }
//        Map<String, BieYangDataDto.SkuInfo> splitSkuMap = new HashMap<>();
//        for (BieYangDataDto splitDataDto : splitDataDtos) {
//            List<BieYangDataDto.SkuInfo> skus = splitDataDto.getSkus();
//            for (BieYangDataDto.SkuInfo skuInfo : skus) {
//                splitSkuMap.put(skuInfo.getBasicInfo().getSkuId() + "#" + skuInfo.getBasicInfo().getProductId(), skuInfo);
//            }
//        }
//
//        for (BieYangDataDto splitDataDto : splitDataDtos) {
//            BieYangInfoSummaryDto infoSummary = splitDataDto.getInfoSummary();
////            List<BieYangDataDto.SkuInfo> skus = splitDataDto.getSkus();
////            for (BieYangDataDto.SkuInfo skuInfo : skus) {
////                splitSkuMap.put(skuInfo.getBasicInfo().getProductId()+"#"+skuInfo.getBasicInfo().getSkuId(),skuInfo);
////            }
//            List<BieYangOrderClearanceInfoDto> subClearanceInfo = splitDataDto.getSubClearanceInfo();
//            if (CollectionUtils.isEmpty(subClearanceInfo)) {
//                continue;
//            }
//            for (BieYangOrderClearanceInfoDto bieYangOrderClearanceInfoDto : subClearanceInfo) {
//                BieYangDataDto newBieYangDataDto = JSON.parseObject(JSON.toJSONString(splitDataDto), BieYangDataDto.class);
//                BieYangInfoSummaryDto newInfoSummary = newBieYangDataDto.getInfoSummary();
//                // 主单号
//                newInfoSummary.setMainOrderId(newInfoSummary.getOrderId());
//                // 单号
//                newInfoSummary.setOrderId(bieYangOrderClearanceInfoDto.getSubOrderNum());
//                // 金额
//                newInfoSummary.setTotalItemPrice(bieYangOrderClearanceInfoDto.getTotalActualPay());
////                newInfoSummary.setTaxAmount(bieYangOrderClearanceInfoDto.gett());
//                // 清关信息
//                newBieYangDataDto.setClearanceInfo(bieYangOrderClearanceInfoDto);
//                List<BieYangSkuIdsInfo> skuIds = bieYangOrderClearanceInfoDto.getSkuIds();
//                List<BieYangDataDto.SkuInfo> newSkuInfos = new ArrayList<>();
//                for (BieYangSkuIdsInfo skuIdInfo : skuIds) {
//                    String key = skuIdInfo.getSkuId() + "#" + skuIdInfo.getProductId();
//                    if (!splitSkuMap.containsKey(key)) {
//                        continue;
//                    }
//                    BieYangDataDto.SkuInfo skuInfo = splitSkuMap.get(key);
//                    newSkuInfos.add(skuInfo);
//                }
//                newBieYangDataDto.setSkus(newSkuInfos);
//
//                bieYangDataDtos.add(newBieYangDataDto);
//            }
//
//        }
//
//
//    }

    private void validateTikTokOrderStatus(List<SkuOrderListItem> skuOrderListItemList) {
        Iterator<SkuOrderListItem> iterator = skuOrderListItemList.iterator();
        while (iterator.hasNext()) {
            SkuOrderListItem item = iterator.next();
            // 订单状态校验
            // 订单状态;1 待确认/待支付-订单创建完毕;
            // 105-已支付;
            // 2-备货中；
            // 101-部分发货;
            // 3-已发货（全部发货）;
            // 4- 已取消;
            // 5 已完成（已收货）;
            if (!item.getOrderStatus().equals(105L)) {
                iterator.remove();
            }
        }
    }

    private List<StoreOrderInfo> assembledStoreOrderInfo(SkuOrderListItem skuOrderListItem, StoreOrder queryStoreOrder) {
        List<StoreOrderInfo> storeOrderInfoList = new ArrayList<>();

        int index = 1;

        // 查询商品唯一属性
        StoreProductAttrValue storeProductAttrValue = getProductAttrValueInfo(skuOrderListItem.getOutSkuId());
//        storeProductAttrValue = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getSelfSourceSkuId, skuOrderListItem.getOutSkuId()));
        log.info("查询商品唯一属性,{}", JSON.toJSONString(storeProductAttrValue));
        if (null == storeProductAttrValue) {
            throw new RuntimeException("根据商户SKU查询商品异常");
        }
        // 根据商品属性匹配商品
        StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getId, storeProductAttrValue.getProductId()));
        log.info("根据商品属性匹配商品,{}", JSON.toJSONString(storeProduct));
        if (null == storeProduct) {
            throw new RuntimeException("商品不存在");
        }

        StoreOrderInfo storeOrderInfo = new StoreOrderInfo();
        storeOrderInfo.setOrderId(queryStoreOrder.getId());
//            storeOrderInfo.setInfo("{}");
        storeOrderInfo.setUnique(UUID.randomUUID().toString());
        storeOrderInfo.setOrderInfoId("SUB_" + queryStoreOrder.getOrderId() + "_" + index);
        storeOrderInfo.setDeliveryAddress(queryStoreOrder.getUserAddress());
        storeOrderInfo.setChildOrderNumber("SUB_" + queryStoreOrder.getOrderId() + "_" + index);
        storeOrderInfo.setStatus(6);
        storeOrderInfo.setRefundStatus(0);
        storeOrderInfo.setIsDel(0);
//            storeOrderInfo.setPayPrice(convertDouble2BigDecimal(clearanceAmount.getNetPrice())
//                    .add(convertDouble2BigDecimal(clearanceAmount.getMerchantCustomsDuty()))
//                    .subtract(convertDouble2BigDecimal(clearanceAmount.getBeyondPromotion()))
//                    .subtract(convertDouble2BigDecimal(clearanceAmount.getMerchantPromotion())));
        // 单价+税费  * 数量
        storeOrderInfo.setPayPrice(convertPrice(skuOrderListItem.getPayAmount()));

        // 优惠
        storeOrderInfo.setDeductionPrice(convertPrice(skuOrderListItem.getPromotionAmount()));
        storeOrderInfo.setCreateTime(new Date());
//            storeOrderInfo.setExchangeRate(convertDouble2BigDecimal(basicInfo.getCustomsDutyRate()));
        // 税费
        storeOrderInfo.setTaxPrice(convertPrice(skuOrderListItem.getTaxAmount()));

        // local商品信息
        BeanUtils.copyProperties(storeProduct, storeOrderInfo);
        storeOrderInfo.setProductId(storeProduct.getId());
        storeOrderInfo.setKeyword(storeProduct.getKeyword());
        storeOrderInfo.setStoreName(storeProduct.getStoreName());
        storeOrderInfo.setCateId(storeProduct.getCateId());
        storeOrderInfo.setVipReducePrice(storeProduct.getVipPrice());
        storeOrderInfo.setNum(skuOrderListItem.getItemNum().intValue());
        storeOrderInfo.setIsWzbsc(false);
        storeOrderInfo.setId(null);

        // 供应商ID
        storeOrderInfo.setSuppliersId(storeProduct.getSuppliersId());

        // 商品购物车信息
        StoreCartResponse storeCartResponse = new StoreCartResponse();
        storeCartResponse.setProductAttrUnique(storeProductAttrValue.getSourceSkuId());
        storeCartResponse.setType("product");
        storeCartResponse.setProductId(storeProductAttrValue.getProductId());
        storeCartResponse.setCartNum(skuOrderListItem.getItemNum().intValue());
        storeCartResponse.setIsNew(true);
        StoreProductCartProductInfoResponse storeProductCartProductInfoResponse = new StoreProductCartProductInfoResponse();
        BeanUtils.copyProperties(storeProduct, storeProductCartProductInfoResponse);
        storeProductCartProductInfoResponse.setAttrInfo(storeProductAttrValue);
        storeProductCartProductInfoResponse.setImage(storeProductAttrValue.getImage());
        storeCartResponse.setProductInfo(storeProductCartProductInfoResponse);

        storeOrderInfo.setInfo(JSON.toJSONString(storeCartResponse));

        storeOrderInfo.setCreateTime(new Date());
        // 扩展字段
        storeOrderInfo.addFeature("merchantProductId", skuOrderListItem.getOutProductId());
        storeOrderInfo.addFeature("productId", skuOrderListItem.getOutProductId());
        storeOrderInfo.addFeature("merchantSkuId", skuOrderListItem.getOutSkuId());
        storeOrderInfo.addFeature("skuId", skuOrderListItem.getOutSkuId());
        storeOrderInfo.addFeature("merId", String.valueOf(queryStoreOrder.getMerId()));
        storeOrderInfoList.add(storeOrderInfo);

        return storeOrderInfoList;
    }

    private StoreProductAttrValue getProductAttrValueInfo(String merchantSkuId) {

        if (StringUtils.isBlank(merchantSkuId)) {
            return null;
        }
        return storeProductAttrValueService.getById(merchantSkuId);
    }


    private StoreOrder assembledStoreOrder(SkuOrderListItem skuOrderListItem, Integer merId) {
        // 清关信息
//        BieYangOrderClearanceInfoDto clearanceInfo = bieYangDataDto.getClearanceInfo();
        // 发件人信息
        PostAddr postAddr = skuOrderListItem.getPostAddr();
        // 订单信息
        StoreOrder storeOrder = new StoreOrder();
        storeOrder.setOutOrderId(skuOrderListItem.getOrderId());
        storeOrder.setOrderId(getOrderId(skuOrderListItem.getOrderId()));
        // 拆单数据
        storeOrder.addFeature(ByCommonConstant.PARENT_ORDER_ID, skuOrderListItem.getParentOrderId());

        storeOrder.setUid(6371);
        storeOrder.setRealName(skuOrderListItem.getEncryptPostReceiver());
        storeOrder.setUserPhone(skuOrderListItem.getPostTel());
        storeOrder.setAreaType(1);
        storeOrder.setUserAddress(postAddr.getProvince().getName() +
                postAddr.getCity().getName() +
                postAddr.getTown().getName() +
                postAddr.getStreet().getName() +
                postAddr.getDetail());

        storeOrder.setFreightPrice(convertPrice(skuOrderListItem.getPostAmount()));
        storeOrder.setTotalNum(skuOrderListItem.getItemNum().intValue());
        storeOrder.setTotalPrice(convertPrice(skuOrderListItem.getOrderAmount()));
        storeOrder.setTotalPostage(convertPrice(skuOrderListItem.getPostAmount()));
        storeOrder.setPayPrice(convertPrice(skuOrderListItem.getPayAmount()));
        storeOrder.setPayPostage(convertPrice(skuOrderListItem.getPostAmount()));
        storeOrder.setDeductionPrice(convertPrice(skuOrderListItem.getPromotionAmount()));
        storeOrder.setCouponId(0);
        storeOrder.setCouponPrice(convertPrice(skuOrderListItem.getPromotionAmount()));
        storeOrder.setPaid(true);
        storeOrder.setPayTime(DateUtil.longToDate(skuOrderListItem.getPayTime() * 1000));

        storeOrder.setPayType(getPayType(skuOrderListItem.getPayType()));
        storeOrder.setCreateTime(new Date());
        storeOrder.setCreateName("SYS");
        // 代发货
        storeOrder.setStatus(6);
        storeOrder.setRefundStatus(0);
        storeOrder.setRefundReasonWapImg("");


        storeOrder.setDeliveryName("");
        storeOrder.setIsDel(false);
        // todo 暂订
        storeOrder.setMerId(merId);
        storeOrder.setShippingType(1);
        storeOrder.setPushStatus(0);

        storeOrder.setProvince(postAddr.getProvince().getName());
        storeOrder.setCity(postAddr.getCity().getName());
        storeOrder.setDistrict(postAddr.getTown().getName());
        storeOrder.setDetail(postAddr.getDetail());
        storeOrder.setIdCard("");
        storeOrder.setSource(9);
        // 支付单号
        storeOrder.setPayNo(skuOrderListItem.getChannelPaymentNo());
        storeOrder.setUnique(UUID.randomUUID().toString());
        storeOrder.setPayName(skuOrderListItem.getEncryptPostReceiver());

        storeOrder.setRemark("DOU_DIAN");
        return storeOrder;
    }

    private String getPayType(Long payType) {
        // 【支付类型】 0-货到付款 1-微信 2-支付宝 3-小程序 4-银行卡 5、余额 7、无需支付（0元单） 8、DOU分期（信用支付） 9、新卡支付
        if (payType == 0L) {
            return "货到付款";
        } else if (payType == 1L) {
            return "微信";
        } else if (payType == 2L) {
            return "支付宝";
        } else if (payType == 3L) {
            return "小程序";
        } else if (payType == 4L) {
            return "银行卡";
        } else if (payType == 5L) {
            return "余额";
        } else if (payType == 7L) {
            return "无需支付（0元单）";
        } else if (payType == 8L) {
            return "DOU分期（信用支付）";
        } else if (payType == 9L) {
            return "新卡支付";
        }
        return "";
    }

    private String getOrderId(String orderId) {
        return "DY" + orderId.replace("-", "");
    }

    public BigDecimal convertPrice(Long value) {
        return null == value ? BigDecimal.ZERO : new BigDecimal(value.toString()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

    }

    private void validateOrderExist(List<SkuOrderListItem> skuOrderListItemList) {
        List<String> orderIds = skuOrderListItemList.stream().filter(item -> StringUtils.isNotBlank(item.getOrderId()))
                .map(SkuOrderListItem::getOrderId)
                .collect(Collectors.toList());
        List<StoreOrder> storeOrderList = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery().in(StoreOrder::getOutOrderId, orderIds));
        if (CollectionUtils.isEmpty(storeOrderList)) {
            return;
        }
        Map<String, StoreOrder> map = storeOrderList.stream().collect(Collectors.toMap(StoreOrder::getOutOrderId, v -> v));
        skuOrderListItemList.removeIf(item -> StringUtils.isBlank(item.getOrderId()) || map.containsKey(item.getOrderId()));
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

    }

}
